package core.customPupupManager
{
	import core.MainManager;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	[Event(name="show_popup", type="core.customPupupManager.CustomPopUpManagerEvent")]
	[Event(name="remove_popup", type="core.customPupupManager.CustomPopUpManagerEvent")]
	public class CustomPopUpManager extends EventDispatcher implements ICustomPopUpManager
	{
		private static var _instance:CustomPopUpManager;
		private var bg:Sprite;                                 //背景
		private var numPopUp:int=0;                            //被popup出来的界面的数目
		private var popupedWindows:Dictionary=new Dictionary();//存储被popup出来的界面，用于回收  
		public function CustomPopUpManager()
		{
			if(_instance==null)
			{
				_instance=this;
			}else
			{
				throw new Error("CustomPopUpManager不能被实例化");
			}
		}
		public static function getInstance():CustomPopUpManager
		{
			if(_instance==null) return new CustomPopUpManager();
			return _instance;
		}

	    public function centerPopUp(popUp:DisplayObject):void
	    {
	    	if(numPopUp==0)
	    	{
	    		createBg();
	    		this.dispatchEvent(new CustomPopUpManagerEvent(CustomPopUpManagerEvent.SHOW_POPUP));
	    	}
	    	popupedWindows[popUp]=popUp;
	        MainManager.getInstance().getContainer(4).addChild(popUp);
	        popUp.x=(MainManager.getInstance().stage.stageWidth-popUp.width)/2;
	        popUp.y=(MainManager.getInstance().stage.stageHeight-popUp.height)/2;
	        numPopUp++;
	    }
	    
	    public function removePopUp(popUp:DisplayObject):void
	    {
	    	if(popUp!=null && popupedWindows[popUp]!=null)//所传的参数不能为空而且所传的对象已经在列表中
	    	{
	    		if(popUp.parent!=null)
	    		{
	    			popUp.parent.removeChild(popUp);
	    		}
	    		popupedWindows[popUp]=null;
	    		popUp=null;
	    		numPopUp--;
	    	}
	    	if(this.numPopUp==0)
	    	{
	    		removeBg();
	    		this.dispatchEvent(new CustomPopUpManagerEvent(CustomPopUpManagerEvent.REMOVE_POPUP));
	    	}
	    }
	    //创建背景
	    private function createBg():void
	    {
	    	if(bg==null)
	    	{
		        bg=new Sprite();
			    bg.graphics.beginFill(0xfdfdfb);
			    bg.alpha=0.4;
			    bg.graphics.drawRect(0,0,MainManager.getInstance().stage.stageWidth,MainManager.getInstance().stage.stageHeight);
			    bg.graphics.endFill();
	    	}
	    	MainManager.getInstance().getContainer(4).addChild(bg);
	    }
	    //删除背景
	    private function removeBg():void
	    {
	    	if(bg!=null)
	    	{
	    		if(bg.parent!=null)
	    		{
	    			bg.parent.removeChild(bg);
	    		}
	    	}
	    }
	}
}